package com.atguigu.union;

/**
 * 用数组模拟并查集
 * void unionElements(p,q)  O(n)
 * boolean isConnected(p,q) O(1)
 */
public class UnionFind1 implements UF {
    private int[]ids;
    public UnionFind1(int size){
        ids=new int[size];
        for (int i = 0; i < ids.length; i++) {
            ids[i]=i;
        }
    }
    //查找元素p对应的集合编号
    private int find(int p){
        if(p<0||p>= ids.length){
            throw new IllegalArgumentException("p is out of bound. ");
        }
        return ids[p];
    }

    @Override
    public int getSize() {
        return ids.length;
    }
    //查看元素p和元素q是否所属一个集合
    @Override
    public boolean isConnected(int p, int q) {
        return find(p)==find(q);
    }
    //合并元素p和元素q所属的集合
    @Override
    public void unionElements(int p, int q) {
        int pID=find(p);
        int qID=find(q);
        if(pID!=qID){
            for (int i = 0; i < ids.length; i++) {
                if(ids[i]==pID){
                    ids[i]=qID;
                }
            }
        }
    }
}
